<?php
require_once realpath(dirname(__FILE__) . '//..//pages.php');
require_once MDL_DATABASE;

/**
 * Performs login
 * 
 * Creates a new User instance and places it in <code>$_SESSION</code> array at position <code>KEY_SESSION_USER</code>
 * 
 * @param string $user username of the user
 * @param string $pass password of the user
 * @return boolean true if <code>$_SESSION</code> array at position <code>KEY_SESSION_USER</code> is set, else false
 */
function login ($user, $pass) {
    require_once CLASS_USER;
    $user = new User (array ('username' => $user, 'password' => $pass, 'last_login' => date('Y-m-d H:i:s')));
    $_SESSION[KEY_SESSION_USER] = serialize($user);
    $registered =  $user->isRegistered ();
    if ($registered) {
        $user->update();
        return true;
    } else {
        return false;
    }
}

/**
 * Performs registration
 * 
 * @param string $user username of the user
 * @param string $pass password of the user
 * @return boolean true on success or false on error or if user is already registered
 */
function register ($user, $pass) {
    /**$u = new User($user, $pass);
    if ($u->isRegistered ()) {
        return false;
    }
    return insert("user", array ("username" => $user, "password" => "PASSWORD('$pass')"));**/
    //header ("location: " . CTRL_DATABASE . "?cmd=insert&table=user&username=$user&password=$pass");
}

/**
 * Performs logout
 * 
 * Unsets the User instance placed in position <code>KEY_SESSION_USER</code>, if any
 * @return boolean true if current user has been unset successfully, false if <code>$_SESSION</code> at position <code>KEY_SESSION_USER</code> doesn't contain anything before unsetting
 */
function logout () {
    if (isset ($_SESSION[KEY_SESSION_USER])) {
        unset ($_SESSION[KEY_SESSION_USER]);
        return true;
    }
    return false;
}

?>
